#!/usr/bin/python
import os
import sys
import time
import re
import shutil

## Init
version = "0.Alpha"
fatalError = False
tvfolder = ""
	
## Gets Configuration
cwd = os.getcwd()
scriptdir = sys.argv[0]
scriptdir = os.path.dirname(scriptdir)
titleFile = scriptdir + "/Shows.titles"
configFile = scriptdir + "/tv-organizer.config"
configFile = configFile.replace("\\","/")
## Checks for the config file
if os.path.exists(configFile):
	pass
else:
	fatalError = "There is no configuration file.  It should be at " + configFile

## Builds list of shows
if fatalError == False:
	configurations = open(configFile,'r').read()
	configurations = configurations.split('\n')
	for configurationLine in configurations:
		configuration = configurationLine.split('=')
		if configuration[0] == 'tvfolder':
			tvfolder = configuration[1]
			tvfolder = tvfolder.replace("\n","")
			tvfolder = tvfolder.replace("\\","/")
			tvfolder = tvfolder.rstrip("/")
dirObj = os.walk(tvfolder)
titles = ""
for t in dirObj:
	for i in t[1]:
		titles += i + "\n"
	break
titleFolder = titles
titles = titles.rstrip("\n")
titles = titles.replace("The ","")
titles = titles.replace("the ","")
titles = titles.replace("THE ","")

def clear():
    os.system(['clear','cls'][os.name == 'nt'])
	
## Prints a splash
def splash():
	print("\n")
	print("\t  _______    __      ____            ")
	print("\t /_  __/ |  / /     / __ \\_________ _")
	print("\t  / /  | | / /_____/ / / / ___/ __ `/")
	print("\t / /   | |/ /_____/ /_/ / /  / /_/ / ")
	print("\t/_/    |___/      \\____/_/   \\__, /  ")
	print("\t                            /____/   ")
	print("\t\t\t\t-by Jo")
	print("\n\t\t Version " + version + "\n\n\n")

## This returns the most likely title to match the folder
def detectTitle(title):
	titleList = title.replace("\\","/")
	titleList = titleList.split("/")
	for i in titleList:
		title = i
	title = title.replace("."," ")
	title = title.title()
	titles_ = titles.split('\n')
	for i in titles_:
		searchTitle = i.replace("."," ")
		pattern = re.findall(searchTitle,title)
		try:
			pattern[0]
			return(i)
		except:
			pass
	return None

## This returns the file extension
def detectExtension(title):
	try:
		return(os.path.splitext(title)[-1].lower())
	except:
		print("\tError with detectExtension")

## This returns the most likely SeaEpi
def detectSeaEpi(title):
	title_ = title.split("/")
	for i in title_:
		title = i
	try:
		pat = [[1,"S","E"],[2,"","X",""],[3,"Season","Episode"]]
		pattern = []
		for patSet in pat:
			try:
				if patSet[0] == 1:
					pattern.append(patSet[1].upper() + "[0-9]" + patSet[2].upper() + "[0-9]")
					pattern.append(patSet[1].lower() + "[0-9]" + patSet[2].lower() + "[0-9]")
					pattern.append(patSet[1].upper() + "[0-9][0-9]" + patSet[2].upper() + "[0-9][0-9]")
					pattern.append(patSet[1].lower() + "[0-9][0-9]" + patSet[2].lower() + "[0-9][0-9]")
					pattern.append(patSet[1].upper() + "[0-9]X" + patSet[2].upper() + "[0-9]")
					pattern.append(patSet[1].lower() + "[0-9]x" + patSet[2].lower() + "[0-9]")
					pattern.append(patSet[1].upper() + "[0-9][0-9]X" + patSet[2].upper() + "[0-9][0-9]")
					pattern.append(patSet[1].lower() + "[0-9][0-9]x" + patSet[2].lower() + "[0-9][0-9]")
					pattern.append(patSet[1].upper() + "[0-9]x" + patSet[2].upper() + "[0-9]")
					pattern.append(patSet[1].lower() + "[0-9]X" + patSet[2].lower() + "[0-9]")
					pattern.append(patSet[1].upper() + "[0-9][0-9]x" + patSet[2].upper() + "[0-9][0-9]")
					pattern.append(patSet[1].lower() + "[0-9][0-9]X" + patSet[2].lower() + "[0-9][0-9]")
					pattern.append(patSet[1].upper() + "[0-9]x" + patSet[2].upper() + "[0-9]")
					pattern.append(patSet[1].lower() + "[0-9]X" + patSet[2].lower() + "[0-9]")
					pattern.append(patSet[1].upper() + "[0-9][0-9]x" + patSet[2].upper() + "[0-9][0-9]")
					pattern.append(patSet[1].lower() + "[0-9][0-9]X" + patSet[2].lower() + "[0-9][0-9]")
				if patSet[0] == 2:
					pattern.append(patSet[1] + "[0-9][0-9]" + patSet[2].upper() + "[0-9][0-9]" + patSet[3])
					pattern.append(patSet[1] + "[0-9][0-9]" + patSet[2].lower() + "[0-9][0-9]" + patSet[3])
					pattern.append(patSet[1] + "[0-9]" + patSet[2].upper() + "[0-9][0-9]" + patSet[3])
					pattern.append(patSet[1] + "[0-9]" + patSet[2].lower() + "[0-9][0-9]" + patSet[3])
					pattern.append(patSet[1] + "[0-9]" + patSet[2].upper() + "[0-9]" + patSet[3])
					pattern.append(patSet[1] + "[0-9]" + patSet[2].lower() + "[0-9]" + patSet[3])
				if patSet[0] == 3:
					pattern.append(patSet[1] + " [0-9][0-9] " + patSet[2] + " [0-9][0-9]")
					pattern.append(patSet[1] + " [0-9] " + patSet[2] + " [0-9]")
					pattern.append(patSet[1] + " [0-9] " + patSet[2] + " [0-9][0-9]")
					pattern.append(patSet[1] + " [0-9][0-9] " + patSet[2] + " [0-9]")
			except:
				pass
		for i in pattern:
			pattern = re.findall(i,title)
			try:
				seaEpi = pattern[0]
				seaEpi = seaEpi.upper()
				season = seaEpi.lstrip("S")
				if len(season.split("E")) == 2:
					seasonArray = season.split("E")
					seasonArray[0] = seasonArray[0].lstrip("0")
					seasonArray[1] = seasonArray[1].lstrip("0")
				if len(season.split("X")) == 2:
					seasonArray = season.split("X")
				return(seasonArray)
			except:
				pass
		return None
	except:
		print("\tError with detectSeaEpi")

## This returns the most likely folder in which it should be placed
def detectDestMajor(title):
	try:
		titles_ = titleFolder.split('\n')
		for i in titles_:
			searchTitle = i.replace(" ",".")
			pattern = re.findall(searchTitle,title)
			try:
				pattern[0]
				return(i)
			except:
				pass
		return None
	except:
		print("\tError with detectDestMajor")

## This returns the most likely folder in which it should be placed
def detectDestMinor(title):
	try:
		season = title.split("E")
		season = season[0]
		season = season.lstrip("S")
		season = season.lstrip("0")
		season = "Season " + season[0]
		return(season)
	except:
		print("\tError with detectDestMinor: " + str(title))

## Progress bar for move
def progBar(file,dest):
	init = os.path.getsize(file)
	max = init
	remainder = 999
	while remainder != 0:
		remainder = max - os.path.getsize(dest)

## Moves the file
def moveFile(file):
	try:
		title = detectTitle(file)
		seaEpi = detectSeaEpi(file)
		season = seaEpi[0]
		if int(seaEpi[0]) < 10:
			season = "0" + seaEpi[0]
		episode = seaEpi[1]
		if int(seaEpi[1]) < 10:
			episode = "0" + seaEpi[1]
		seaEpi = "S" + season + "E" + episode
		extension = detectExtension(file)
		destinationMajor = detectDestMajor(file)
		destinationMajor = ""
		destinationMinor = title + "/" + detectDestMinor(seaEpi)
		destination = destinationMajor + destinationMinor
		folderDest = tvfolder + "/" + destination
		fileDest = tvfolder + "/" + destination + "/" + title + " " + seaEpi + extension
		if not os.path.exists(folderDest):
			os.makedirs(folderDest)
		print("Moving " + file + " > " + fileDest)
		shutil.move(file,fileDest)
		return(fileDest)
	except:
		pass
		#print("\tError with moveFile: " + file)

def listDir(d):
	if not os.path.isdir(d):
		files.append(d)
	else:
		for item in os.listdir(d):
			listDir((d + '/' + item) if d != '/' else '/' + item)

## Executes the prcedure to organize the files	
clear()
splash()
files = []
listDir(sys.argv[1])
for i in files:
	moveFile(i)







